// pages/cartshop/cartshop.js
const app = getApp();
app.func.page({

    /**
     * 页面的初始数据
     */
    data: {
        cartshoplist: '',
        allcount: 0,
        totalPrice: '0.00',//初始价格
        selectAll: false,//是否全选
        hasList: false,//当购物车为空的时候
        addresstau: false,
        addressArr: '',
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        if(options.skuid != null) {
            this.setData({
                items: [{id:options.skuid, count:1}]
            }, () => {
                this.precreate();
            })
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.myinfos();
    },

    onModal: function (args) {
        let cartshoplist = args.carts;
        this.setData({
            items: cartshoplist,
        }, () => {
            this.precreate();
        })
    },

    precreate() {
        let carts = this.data.items; // 获取购物车列表//cartshoplist
        let address = this.data.addressArr;
        app.func.postPromise("/order/precreatev2", {
            items: carts,
            address: address
        }).then(([code, res]) => {
            if (code == 200) {
                this.setData({
                    cartshoplist: res.data.items,
                    orderable: res.data.orderable,
                    total: res.data.paid,
                    ship_account_type: res.data.ship_account_type,
                    balance: res.data.balance,
                    credit: res.data.credit
                })
            }
        });
    },

    makeorder: function () {
        let carts = this.data.items; // 获取购物车列表//cartshoplist
        console.log(carts)
        let address = this.data.addressArr;
        return app.func.postPromise('/order/createv2', {
            items: carts,
            address: address
        }).then(([code, res]) => {
            if (code === 6001) {
                return this.wechatPay(res.data);
            }
            if (code === 200) {
                wx.redirectTo({
                    url: '/pages/about/card/orderlist/detail/detail?id=' + res.data
                })
                return;
                // app.func.toastPromise("下单成功");
            }
            if (code == 3003) {
                app.func.toastPromise('该商品暂不支持该地区配送')
                this.setData({
                    forset:true
                })
            }
            if (code == 6002) {
                app.func.toastPromise('请先结清月结账款')
            }
            if (code == 1102) {
                app.func.toastPromise('商品已下架')
            }
            if (code == 6004) {
                app.func.toastPromise('账户余额不足')
            }
            if (code == 3002) {
                this.setData({showchoose: true});
            } else {
                app.func.toastPromise(res.message, 'none', 2500);
            }

        });
    },

    wechatPay: function (orderid) {
        var paymentid = null;
        var checkstatus = function (status) {
            if (status === 1) {
                return status;
            }
            return app.func.toastPromise('支付成功')
                .then(() => {
                    return app.func.getPromise('/order/status/' + orderid)
                        .then(([code, res]) => {
                            return res.data.status;
                        }, app.func.reject);
                });
        };

        return app.func.postPromise('/order/pay/' + orderid, {})
            .then(([code, res]) => {
                if (code === 200) {
                    console.log(res)
                    var param = res.data;
                    paymentid = res.data.paymentid;
                    return app.func.promise((resolve, reject) => {
                        wx.requestPayment({
                            timeStamp: param.timeStamp,
                            nonceStr: param.nonceStr,
                            package: param.package,
                            signType: param.signType,
                            paySign: param.paySign,
                            success(res) {
                                resolve(0);
                            },
                            fail(res) {
                                return app.func.postPromise("/order/unpay/" + orderid, {})
                                    .then(reject);
                            }
                        });
                    });
                } else {
                    return app.func.reject();
                }
            })
            .then(checkstatus).then(checkstatus).then(checkstatus)
            .then((status) => {
                if (status === 1) {
                    wx.redirectTo({
                        url: '/pages/about/card/orderlist/detail/detail?id=' + orderid
                    });
                    return;
                } else {
                    return app.func.toastPromise('支付失败')
                        .then(app.func.reject);
                }
            });
    },


    selectList(e) {
        const index = e.currentTarget.dataset.index; // 获取data- 传进来的index
        let carts = this.data.cartshoplist; // 获取购物车列表
        const selected = carts[index].checked; // 获取当前商品的选中状态
        carts[index].checked = !selected; // 改变状态
        this.setData({
            cartshoplist: carts
        });
        this.getTotalPrice(); // 重新获取总价
    },


    // 增加数量
    incCount(e) {
        const id = e.currentTarget.dataset.id;
        let carts = this.data.items;
        carts = carts.map(function (c) {
            if(id == c.id) {
                return {id:c.id, count: c.count+1};
            }
            return c;
        })
        this.setData({
            items: carts
        }, () => {
            this.precreate();
        })
    },


    //减少数量
    decCount: function (e) {
        const id = e.currentTarget.dataset.id;
        let carts = this.data.items;
        carts = carts.map(function (c) {
            if(id == c.id && c.count > 1) {
                return {id:c.id, count: c.count - 1};
            }
            return c;
        })
        this.setData({
            items: carts
        }, () => {
            this.precreate();
        })
    },

    myinfos() {
        app.func.getPromise('/my/info')
            .then(([code, res]) => {
                console.log(res.message)
                this.setData({
                    myinfo: res.message
                });
            })
    },

    chooseAddress: function () {
        this.navigateModal('/pages/about/myaddress/oursaddress/oursaddress', {})
            .then((res) => {
                if (res != null && res.address != null) {
                    let addressArr = res.address;
                    if (addressArr.length == 0) {
                        this.setData({
                            addresstau: false
                        })
                    } else {
                        this.setData({
                            addressArr: addressArr,
                            addresstau: true
                        })
                    }
                    this.precreate();
                }
            })
    },
    noMakeorder:function(){
        let address = this.data.addressArr;
     
        if(address == ''){
            app.func.toastPromise('请选择地址', 'none', 2500);
        }
    }
})